package com.linksoul.service;

import com.linksoul.domain.MbtiOption;
import com.linksoul.domain.MbtiResult;
import com.linksoul.domain.TestDimensionDetail;
import com.linksoul.domain.UserResponse;
import com.linksoul.mapper.MbtiQuestionMapper;
import com.linksoul.mapper.MbtiRequestLogMapper;
import com.linksoul.mapper.TestDimensionDetailMapper;
import com.linksoul.mapper.UserResponseMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/05/01/16:18
 **/
@Service
@RequiredArgsConstructor
public class MbtiCalculatorService {
    private final MbtiQuestionMapper optionMapper;
    private final UserResponseMapper userResponseMapper;
    private final TestDimensionDetailMapper testDimensionDetailMapper;
    private final MbtiRequestLogMapper logMapper;

    @Transactional
    public String calculateMbti(Map<Long, Long> answers, String requestId) {
        // 初始化维度得分
        Map<String, Integer> dimensionTotals = initDimensionMap();
        List<UserResponse> responses = new ArrayList<>();

        // 处理每个答案
        answers.forEach((questionId, optionId) -> {
            UserResponse userResponse =new UserResponse();
            userResponse.setRequestId(requestId);
            userResponse.setQuestionId(questionId.intValue());
            userResponse.setOptionId(optionId);
            // 记录答题明细
            responses.add(userResponse);

            // 计算维度得分
            MbtiOption option = optionMapper.selectOptionById(optionId);
            option.getDimensionScores().forEach((dim, score) ->
                    dimensionTotals.merge(dim, score, Integer::sum)
            );
        });

        // 批量插入答题记录
        if (!responses.isEmpty()) {
            userResponseMapper.batchInsert(responses);
        }

        // 构建MBTI结果
        String mbtiType = buildMbtiResult(dimensionTotals);
        TestDimensionDetail testDimensionDetail = new TestDimensionDetail();
        testDimensionDetail.setRequestId(requestId);
        testDimensionDetail.setEiScore(dimensionTotals.get("EI"));
        testDimensionDetail.setSnScore(dimensionTotals.get("SN"));
        testDimensionDetail.setTfScore(dimensionTotals.get("TF"));
        testDimensionDetail.setJpScore(dimensionTotals.get("JP"));
        // 保存维度详情
        testDimensionDetailMapper.insert(testDimensionDetail);

        // 保存主结果
        saveResult(requestId, dimensionTotals, mbtiType);

        return mbtiType;
    }

    private Map<String, Integer> initDimensionMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("EI", 0);
        map.put("SN", 0);
        map.put("TF", 0);
        map.put("JP", 0);
        return map;
    }

    private String buildMbtiResult(Map<String, Integer> scores) {
        return new StringBuilder()
                .append(scores.get("EI") >= 0 ? "E" : "I")
                .append(scores.get("SN") >= 0 ? "S" : "N")
                .append(scores.get("TF") >= 0 ? "T" : "F")
                .append(scores.get("JP") >= 0 ? "J" : "P")
                .toString();
    }

    private void saveResult(String requestId, Map<String, Integer> scores, String mbtiType) {
        MbtiResult result = new MbtiResult()
                .setRequestId(requestId)
                .setMbtiType(mbtiType)
                .setEiScore(scores.get("EI"))
                .setSnScore(scores.get("SN"))
                .setTfScore(scores.get("TF"))
                .setJpScore(scores.get("JP"))
                .setCreatedAt(new Date());

        //resultMapper.insert(result);
        logMapper.updateStatus(requestId, "completed",new Date(),2000,90, mbtiType);
    }
}
